package com.korion.lamedemo;

import androidx.appcompat.app.AppCompatActivity;

import android.content.res.AssetManager;
import android.os.Bundle;
import android.os.Environment;
import android.os.Looper;
import android.view.View;
import android.widget.TextView;

import com.korion.lame.Mp3Encoder;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";
    private TextView tv_log;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        findViewById(R.id.btn_encode_mono).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        String testFile = "pcm_44100_mono_16bit_le.raw";
                        encodePCM(testFile, 44100, 16, 1);
                    }
                }).start();
            }
        });

        findViewById(R.id.btn_encode_stereo).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        String testFile = "pcm_44100_stereo_16bit_le.raw";
                        encodePCM(testFile, 44100, 16, 2);
                    }
                }).start();
            }
        });

        tv_log = findViewById(R.id.tv_log);

    }


    private void encodePCM(String fileName, int sampleRate, int bitDepth, int channels){
        File music = getExternalFilesDir(Environment.DIRECTORY_MUSIC);
        if (!music.exists()) {
            music.mkdirs();
        }
        File outFile = new File(music, fileName);
        if (outFile.exists()) {
            outFile.delete();
        }
        if (copyAssetsFileTo(fileName, outFile)){
            String mp3path = outFile.getParent() + "/"+fileName+".mp3";
            log("mp3 encoder init...");
            int init = Mp3Encoder.init(outFile.getAbsolutePath(),
                    channels, bitDepth, sampleRate, mp3path);
            if (init >= 0) {
                log("mp3 encoder init success");
                log("start encoding...");
                int code = Mp3Encoder.encode();
                log("end encoding: "+code);
                Mp3Encoder.destroy();
                log("destroy");
            } else {
                log("mp3 encoder init fail");
            }
        }
    }

    private InputStream getFileFromAssets(String name) throws IOException {
        AssetManager am = getAssets();
        return am.open(name);
    }

    private boolean copyAssetsFileTo(String assetRes, File outFile){
        log("copy assets file["+assetRes+"] to "+outFile.getAbsolutePath()+"...");
        try {
            InputStream in = getFileFromAssets(assetRes);
            FileOutputStream os = new FileOutputStream(outFile);
            byte[] buffer = new byte[4096];
            int count = in.read(buffer);
            do {
                os.write(buffer, 0, count);
                count = in.read(buffer);
            } while (count != -1);
            os.flush();
            in.close();
            os.close();
            log("copy file success.");
            return true;
        } catch (IOException e) {
            e.printStackTrace();
        }
        log("copy wav file fail.");
        return false;
    }


    private void log(String message){
        printlog(currentFormatTime(), message);
    }

    private void printlog(final String time, final String message){
        if (Looper.getMainLooper().getThread() == Thread.currentThread()){
            tv_log.append(time +": "+message+"\n");
        } else {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    printlog(time, message);
                }
            });
        }
    }

    private static final SimpleDateFormat format = new SimpleDateFormat("yyyy.MM.dd hh:mm:ss");

    private String currentFormatTime(){
        return formatTime(System.currentTimeMillis());
    }

    public static String formatTime(long time) {
        return format.format(time) + String.format(".%03d", time % 1000);
    }
}

